const Article = require('models/Article')
const pagify = require('utils/pagify')

const get = async (id) => {
  const article = await Article.where({ id, status: 1 }).fetch()
  return article
}

const search = async (query, pageIndex=1, pageSize=10) => {
  const q = await Article.query((qb) => {
    qb.where({ status: 1 })
    return qb
  })
  return pagify.bookshelf(q, pageIndex, pageSize)
}

const remove = async (id) => {
  await Article.where({
    id
  }).save({
    status: 0
  }, {
    patch: true
  })
}

const create = async (data) => {
  if (!data.title || !data.content || !data.category) {
    throw new BizError('缺少参数')
  }
  let article = new Article(data)
  article.set('status', 1)
  await article.save()
  return article
}

const save = async (id, article) => {
  const { title, content, category } = article
  await Article.where({
    id
  }).save({
    title,
    content,
    category
  }, { patch: true })
}


module.exports = {
  get,
  save,
  create,
  remove,
  search
}